﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team (cellcloudproject@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellSpeakerConnectorHandler.h"
#include "CellSpeaker.h"
#include "CellPacket.h"
#include "CellMessage.h"
#include "CellTalkPacketDefinition.h"
#include "CellLoggerManager.h"

namespace cell
{

#define RECEIVE_CACHE_SIZE 8192

//-----------------------------------------------------------------------
SpeakerConnectorHandler::SpeakerConnectorHandler(Speaker* speaker)
	: mSpeaker(speaker)
{
	mReceiveCache = CELL_ALLOC_T(char, RECEIVE_CACHE_SIZE, MEMCATEGORY_GENERAL);
	memset(mReceiveCache, 0x0, RECEIVE_CACHE_SIZE);
}
//-----------------------------------------------------------------------
SpeakerConnectorHandler::~SpeakerConnectorHandler(void)
{
	CELL_FREE(mReceiveCache, MEMCATEGORY_GENERAL);
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::sessionCreated(Session* session)
{
	mSpeaker->fireSessionCreated(session);
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::sessionDestroyed(Session* session)
{
	mSpeaker->fireSessionDestroyed(session);
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::sessionOpened(Session* session)
{
	mSpeaker->fireSessionOpened(session);
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::sessionClosed(Session* session)
{
	mSpeaker->fireSessionClosed(session);
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::messageReceived(Session* session, Message* message)
{
	uint size = message->length();
	if (size > RECEIVE_CACHE_SIZE)
		return;

	memset(mReceiveCache, 0x0, RECEIVE_CACHE_SIZE);
	message->get(mReceiveCache);

	Packet packet;
	if (Packet::unpack(&packet, mReceiveCache, size))
	{
		interpret(session, &packet);
	}
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::messageSent(Session* session, Message* message)
{
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::errorOccurred(uint16 errorCode, Session* session)
{
}
//-----------------------------------------------------------------------
void SpeakerConnectorHandler::interpret(Session* session, Packet* packet)
{
	// 取出 TAG
	char tag[PSL_TAG] = {0x0};
	packet->getTag(tag);

	// 匹配命令
	int cmd = matchPacketTag(tag);

	switch (cmd)
	{
	case ACT_DIALOGUE:
	{
		// 进行对话处理
		mSpeaker->processDialogue(packet, session);
		break;
	}
	case ACT_REQUEST:
	{
		// 启动心跳
		mSpeaker->startHeartbeat(session);

	#if CELL_DEBUG_MODE
		char log[128] = {0x0};
		sprintf(log, "[CC] Cellet '%s' has called at %s:%d"
			, mSpeaker->getCelletIdentifier().c_str()
			, mSpeaker->getAddress()->getHostAddress().c_str()
			, mSpeaker->getAddress()->getPort());
		LoggerManager::getSingleton().log(log);
	#endif // CELL_DEBUG_MODE
		break;
	}
	case ACT_CHECK:
	{
		// 获取对端内核的标签
		char ntag[64] = {0x0};
		packet->getSubsegment(ntag, 1);

		// 记录标签
		mSpeaker->recordTag(ntag);

		// 发送事件
		mSpeaker->fireContacted();

		// 请求 Cellet
		mSpeaker->requestCellet(session);

		break;
	}
	case ACT_INTERROGATE:
	{
		mSpeaker->requestCheck(packet, session);
		break;
	}
	default:
		break;
	}
}
//-----------------------------------------------------------------------
inline int SpeakerConnectorHandler::matchPacketTag(const char* tag)
{
	if (tag[2] == TPT_DIALOGUE_B3 && tag[3] == TPT_DIALOGUE_B4)
	{
		return SpeakerConnectorHandler::ACT_DIALOGUE;
	}
	else if (tag[2] == TPT_REQUEST_B3 && tag[3] == TPT_REQUEST_B4)
	{
		return SpeakerConnectorHandler::ACT_REQUEST;
	}
	else if (tag[2] == TPT_CHECK_B3 && tag[3] == TPT_CHECK_B4)
	{
		return SpeakerConnectorHandler::ACT_CHECK;
	}
	else if (tag[2] == TPT_INTERROGATE_B3 && tag[3] == TPT_INTERROGATE_B4)
	{
		return SpeakerConnectorHandler::ACT_INTERROGATE;
	}

	return SpeakerConnectorHandler::ACT_UNKNOWN;
}

} // end namespace cell
